<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <textarea name="content" id="t1" cols="40" rows="20"></textarea>
    <button onclick="addPasteListener()">启动</button>
    <button onclick="removePasteListener()">关闭</button>
    <button onclick="copyToClickBoard()">复制</button>
    <button onclick="pasteToClickBoard()">粘贴</button>
</body>
<script>
    // 增加粘贴监听
    function addPasteListener() {
        document.addEventListener('paste', this.beforPasteHandler)
    }
    // 粘贴时把tab和换行替换成逗号
    function beforPasteHandler(event) {
        let paste = (event.clipboardData || window.clipboardData).getData('text')
        // paste = paste.replace(/(\r|\n|\t)/g, ',')
        // paste = paste.replace(/(,,)/g, ',')
        // if (paste.charAt(paste.length - 1) === ',') {
        //     paste = paste.substr(0, paste.length - 1)
        // }
        // 写入操作,这里写的只是参考(实际上踩坑了,不能直接修改DOM,要修改虚拟DOM绑定的值才行,所以这里最好把时间绑定到需要用到组件,例如FormItem或者Input组件)
        // const selection = document.activeElement // 获取当前焦点所在元素
        // if (!selection || selection.tagName.toUpperCase() === 'BODY') return false
        // selection.value = selection.value + paste
        copyToClickBoard()
        // event.preventDefault()
    }
    // 移除离开页面提示
    function removePasteListener() {
        document.removeEventListener('paste', this.beforPasteHandler)
    }

    function copyToClickBoard() {
        var content = "https://upload.chfwork.cloud:8080/";
        navigator.clipboard.writeText(content)
            .then(() => {
                // pasteToClickBoard()
                alert("上传成功")
                // console.log("Text copied to clipboard...")
            })
            .catch(err => {
                console.log('图片上传失败', err);
            })
    }
    function pasteToClickBoard() {
        // var content = "https://upload.chfwork.cloud:8080/";
        // navigator.clipboard.readText(content)
        navigator.clipboard.readText()
            .then((clipText) => {
                console.log(clipText);
            })
            .catch((err) => {
                console.log("粘贴失败");
            })
    }
</script>

</html>